package FeedMaker;

import java.util.Enumeration;
import java.util.Hashtable;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.os.Environment;

public class DdanjiFeeds
{
	private Hashtable<String,String> feeds_;
	private String save_path_;
	
	public DdanjiFeeds( String save_path )
	{
		feeds_ = new Hashtable<String,String>();
		save_path_ = save_path;
		
		load();
	}
	
	synchronized public void add( String feed, String feed_title )
	{
		//String feed_title = feeds_.get(feed);
		
		//if( feed_title == null )
		//{
		feeds_.put(feed, feed_title );
		//}
		
		save();
	}
	
	synchronized public void remove( String feed )
	{
		feeds_.remove(feed);
		
		save();
	}
	
	synchronized public void get_elements( Hashtable<String, String> feeds ) {
		
		if( feeds != null )
		{
			feeds.clear();
			
			for(Enumeration<String> f = feeds_.keys(); f.hasMoreElements(); )
			{
				String feed = f.nextElement();
				
				String feed_title = feeds_.get(feed);
				
				feeds.put( feed, feed_title );
			}
		}
	}
	
	synchronized public void save()
	{		
		XmlWriter writer = new XmlWriter();
		
		if( writer.doc_ != null )
		{	
			Element root = writer.doc_.createElement( "feeds" );
			writer.doc_.appendChild( root );
			
			for( Enumeration<String> f = feeds_.keys(); f.hasMoreElements(); )
			{
				String feed = f.nextElement();
				
				String feed_title = feeds_.get(feed);
				
				Element elem = writer.doc_.createElement( "feed_info" );
				
				elem.setTextContent( feed );
				
				elem.setAttribute("title", feed_title);
				
				root.appendChild( elem );
			}
			
			writer.save( Environment.getExternalStorageDirectory() + "/" + save_path_ + "ddanji_feed_info.xml" );
		}
	}
	
	synchronized private void load()
	{			
		XmlParser parser = new XmlParser( Environment.getExternalStorageDirectory() + "/" + save_path_ + "ddanji_feed_info.xml" );
		
		if( parser.doc_ != null )
		{			
			NodeList nodeList = parser.doc_.getElementsByTagName( "feed_info" );
			
			for(int i=0; i<nodeList.getLength(); ++i)
			{
				Node feed_node = nodeList.item(i);
				
				String feed = feed_node.getTextContent();
				
				Node titleAttribute = feed_node.getAttributes().getNamedItem("title");
				
				if( titleAttribute != null )
				{
					String feed_title = titleAttribute.getNodeValue();
					
					if( feed != null && feed.length() > 0 )
						feeds_.put( feed, feed_title );
				}
			}
		}				
	}
}